package org.easybuy.daoimpol;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.easybuy.dao.BaseDao;
import org.easybuy.dao.NewsDao;
import org.easybuy.entity.News;

public class NewsDaoImopl extends BaseDao implements NewsDao {

	@Override
	public List<News> getIndexNews() {
		List<News> list = new ArrayList<News>();
		ResultSet rs = null;
		News news = null;
		String sql = "SELECT *FROM `easybuy_news` ORDER BY `createTime` DESC LIMIT 5";
		rs = this.exxcuteQuery(sql);
		try {
			while (rs.next()) {
				news = new News();
				news.setId(rs.getInt("id"));
				news.setTitle(rs.getString("title").toString());
				news.setContent(rs.getString("content").toString());
				news.setCreateTime(rs.getString("createTime").toString());
				list.add(news);

			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(connection, pstmt, rs);
		}
		return list;
	}

	// 分页查询新闻
	@Override
	public List<News> getPageNewsList(int pageNo, int pageSize)
			throws SQLException {
		List<News> list = new ArrayList<News>();
		ResultSet rs = null;
		String sql = "select *from `easybuy_news` ORDER BY `createTime` DESC LIMIT ?,?";
		rs = this.exxcuteQuery(sql, (pageNo - 1) * pageSize, pageSize);
		News news = null;
		while (rs.next()) {
			news = new News();
			news.setId(rs.getInt("id"));
			news.setTitle(rs.getNString("title"));
			news.setContent(rs.getString("content"));
			news.setCreateTime(rs.getString("createTime"));
			list.add(news);
		}
		return list;
	}
	//新闻总计路数
	@Override
	public int getTotalCount() throws SQLException {
		ResultSet rs = null;
		String sql = "SELECT COUNT(1) FROM `easybuy_news`";
		int count = -1;
		try {
			rs = this.exxcuteQuery(sql);
			rs.next();
			count = rs.getInt(1);
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		} finally {
			BaseDao.closeAll(connection, pstmt, rs);
		}
		return count;
	}
	//根据ID查找新闻
	@Override
	public List<News> getNewsById(int id) {
		List<News> list = new ArrayList<News>();
		ResultSet rs = null;
		String sql = "select *from `easybuy_news` where id=?";
		rs = this.exxcuteQuery(sql, id);
		News news = null;
		try {
			while (rs.next()) {
				news = new News();
				news.setId(rs.getInt("id"));
				news.setTitle(rs.getNString("title"));
				news.setContent(rs.getString("content"));
				news.setCreateTime(rs.getString("createTime"));
				list.add(news);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			BaseDao.closeAll(connection, pstmt, rs);
		}
		return list;
	}
}
